package initia

import (
	"github.com/google/uuid"
	"github.com/hashicorp/consul/api"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"gopkg.in/yaml.v3"
	"strconv"

	"gitee.com/yumo01/zg5-learn/global"
)

func init() {
	Logger()
	Viper()
	Nacos()
	Consul()
	Mysql()
}

func Logger() {
	logger, err := zap.NewProduction()
	if err != nil {
		panic(err)
	}
	zap.ReplaceGlobals(logger)
	zap.S().Info("zap日志初始化完成")
}

func Viper() {
	v := viper.New()
	v.SetConfigFile("./conf/config.yaml")
	err := v.ReadInConfig()
	if err != nil {
		zap.S().Fatal("读取本地配置失败", err)
	}
	err = v.Unmarshal(&global.Conf)
	if err != nil {
		zap.S().Fatal("解析配置失败", err)
	}
	zap.S().Info("viper配置初始化完成")
}

func Nacos() {
	sc := []constant.ServerConfig{
		{
			IpAddr: global.Conf.Nacos.ServerConfig.IpAddr,
			Port:   global.Conf.Nacos.ServerConfig.Port,
		},
	}
	cc := constant.ClientConfig{
		NamespaceId: global.Conf.Nacos.ClientConfig.NamespaceId,
		LogLevel:    "debug",
	}
	cci, err := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": sc,
		"clientConfig":  cc,
	})
	if err != nil {
		zap.S().Fatal("创建远程配置实例失败")
	}
	s, err := cci.GetConfig(vo.ConfigParam{
		DataId: global.Conf.Nacos.ConfigParam.DataId,
		Group:  global.Conf.Nacos.ConfigParam.Group,
	})
	if err != nil {
		zap.S().Fatal("获取远程配置失败", err)
	}
	err = yaml.Unmarshal([]byte(s), &global.Conf)
	if err != nil {
		zap.S().Fatal("解析远程配置失败", err)
	}
	zap.S().Info("nacos配置初始化完成")
	zap.S().Info(global.Conf)
}

func Consul() {
	conf := api.DefaultConfig()
	conf.Address = global.Conf.Consul.Host + ":" + strconv.Itoa(global.Conf.Consul.Port)
	client, err := api.NewClient(conf)
	if err != nil {
		zap.S().Fatal("创建consul实例失败")
	}

	asr := api.AgentServiceRegistration{
		ID:      uuid.New().String(),
		Name:    global.Conf.Name,
		Address: "10.3.195.26",
		Port:    global.Conf.Port,
		Check: &api.AgentServiceCheck{
			GRPC:                           "10.3.195.26" + ":" + strconv.Itoa(global.Conf.Port),
			Interval:                       "5s",
			Timeout:                        "5s",
			DeregisterCriticalServiceAfter: "10s",
		},
	}

	err = client.Agent().ServiceRegister(&asr)
	if err != nil {
		zap.S().Fatal("注册服务失败", err)
	}
	zap.S().Info("consul配置初始化完成")
}
